package com.truthbean.jeetb.cms.sys.servlet;

import com.truthbean.jeetb.cms.sys.handler.LoginHandler;
import com.truthbean.jeetb.model.sys.entity.User;

import javax.inject.Inject;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by TruthBean on 2016-10-09 17:39.
 */
@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {

    @Inject
    private User user;
    @Inject
    private LoginHandler loginHandler;

    /**
     * Processes requests for both HTTP `GET` and `POST` methods.
     * @param request servlet request
     * *
     * @param response servlet response
     * *
     * throws ServletException if a servlet-specific error occurs
     * *
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //populate the credentials request scoped beans with
        //the user provided username and password
        String name = request.getParameter("username");
        if(name != null && !name.isEmpty()){
            user.setName(name);
        }

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        try {
            //attempt to login using the provided credentials
            loginHandler.login();

            //Print appropriate logged in status message
            if (loginHandler.isLogin()) {
                out.println("Successfully Logged In as: " + user.getName());
            } else {
                out.println("Login Failed: Check username and/or password.");
            }
        } finally {
            out.close();
        }
    }

    /**
     * Handles the HTTP `GET` method.
     * @param request servlet request
     * *
     * @param response servlet response
     * *
     * @throws IOException if a servlet-specific error occurs
     * *
     * @throws IOException if an I/O error occurs
     */
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP `POST` method.
     * @param request servlet request
     * *
     * @param response servlet response
     * *
     * @throws IOException if a servlet-specific error occurs
     * *
     * @throws IOException if an I/O error occurs
     */
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        processRequest(request, response);
    }
}
